<script setup>

import {ref} from "vue";
import {ElMessage} from "element-plus";
// 引入添加节点的api
import {getNodeTreeApi, deleteNodeApi} from "@/service/auth.js";
// 导入添加节点的组件
import NodeAdd from "./components/node-add.vue";
import NodeEdit from "./components/node-edit.vue";

const treeData = ref([]);
const fetchTreeData = () => {
  getNodeTreeApi().then((res) => {
    treeData.value = res.data.tree;
  });
};

// 显示添加节点的抽屉
const nodeAddRef = ref(null);
const showAddDrawer = () => {
  nodeAddRef.value.openDrawer();
};

// 显示编辑节点的抽屉
const nodeEditRef = ref(null);
const showEditNode = (row) => {
  nodeEditRef.value.openDrawer(row);
};

const deleteNode = (row) => {
  const {id} = row;
  // 提示是否删除
  ElMessage.confirm({
    title: "提示",
    message: "确定删除该节点吗？",
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "el-button",
    cancelButtonClass: "el-button--text",
    callback: (action) => {
      if (action === "confirm") {
        deleteNodeApi(id).then((res) => {
          ElMessage.success(res.msg);
          fetchTreeData();
        });
      }
    },
  });
}

onMounted(() => {
  fetchTreeData();
});
</script>

<template>

  <el-main>
    <div class="toolbar">
      <el-button type="danger" @click="showAddDrawer">新增节点</el-button>
      <el-button type="primary" @click="fetchTreeData">刷新</el-button>
    </div>

    <el-table :data="treeData" border row-key="id" width="100%">
      <el-table-column prop="title" label="节点" />
      <el-table-column label="图标">
        <template #default="{row}">
          <el-icon size="16" v-if="row.icon">
            <component :is="row.icon"/>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="is_menu" label="节点类型">
        <template #default="{row}">
          <span v-if="row.is_menu === 1">菜单</span>
          <span v-else-if="row.is_menu === 2">目录</span>
          <span v-else-if="row.is_menu === 3">按钮</span>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路由"/>
      <el-table-column prop="sort" label="排序"/>
      <el-table-column prop="status" label="开启状态">
        <template #default="{row}">
          <el-switch v-model="row.status" :active-value="1" :inactive-value="0" active-text="开启"
                     inactive-text="关闭"/>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="showEditNode(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="deleteNode(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <node-add ref="nodeAddRef" @reload="fetchTreeData"/>
    <node-edit ref="nodeEditRef" @reload="fetchTreeData"/>
  </el-main>

</template>

<style scoped lang="less">
.node-head {
  display: flex;
  align-items: center;
  .node-title {
    margin-left: 8px;
  }
}
</style>
